package com.manong.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.manong.aspect.AutoFill;
import com.manong.config.redis.RedisService;
import com.manong.entity.LoginLog;
import com.manong.entity.Role;
import com.manong.service.LoginLogService;
import com.manong.utils.JwtUtils;
import com.manong.utils.Result;
import com.manong.vo.query.LoginLogQueryVo;
import org.apache.ibatis.annotations.Param;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/loginInfo")
public class LoginLogController {
    @Resource
    LoginLogService loginLogService;
    @Resource
    private RedisService redisService;
    @Resource
    private JwtUtils jwtUtils;
    /**
     * 查询登录日志列表
     * @param loginLogQueryVo
     * @return
     */
    @GetMapping("/list")
    public Result list(LoginLogQueryVo loginLogQueryVo){
        IPage<LoginLog> page = new Page<LoginLog>();
        page.setCurrent(loginLogQueryVo.getPageNo());
        page.setSize(loginLogQueryVo.getPageSize());
        loginLogService.findLoginListByUsername(page,loginLogQueryVo);
        return Result.ok(page);
    }

    /**
     * 删除登录日志
     * @param ids
     * @return
     */
    @AutoFill(menu = "登录日志", type = "删除")
    @DeleteMapping("/delete/{ids}")
    @PreAuthorize("hasAuthority('sys:loginlog:delete')")
    public Result delete(@PathVariable List<Long> ids){

        if(loginLogService.delete(ids)){
            return Result.ok().message("删除成功");
        }else {
            return Result.error().message("删除失败");
        }
    }
    @GetMapping("/lists")
    public Result network(LoginLogQueryVo loginLogQueryVo){
        Set<String> allKeys = redisService.getAllKeys();
        List<String> KeyCollect = allKeys.stream().filter(key -> key.startsWith("token_")).collect(Collectors.toList());
        ArrayList<LoginLog> list = new ArrayList<>();
        for (String s : KeyCollect) {
            String token = redisService.get(s);
            String username = jwtUtils.getUsernameFromToken(token);
            List<LoginLog> loginLogs = loginLogService.list(new QueryWrapper<LoginLog>()
                    .eq("username", username)
                    .orderByDesc("login_time")
                    .last("LIMIT 1"));
            if (!loginLogs.isEmpty()) {
                list.add(loginLogs.get(0));
            }
        }
        IPage<LoginLog> page = new Page<LoginLog>();
        page.setCurrent(loginLogQueryVo.getPageNo());
        page.setSize(loginLogQueryVo.getPageSize());
        page.setRecords(list);
        page.setTotal(list.size());
        return Result.ok(page);
    }

    @AutoFill(menu = "踢人下线", type = "踢下线")
    @PostMapping("/deleteNet")
    @PreAuthorize("hasAuthority('sys:network:delete')")
    public Result deleteNet(@RequestBody Map<String, String> payload){
        String username = payload.get("username");
        System.out.println("username = " + username);
        Set<String> allKeys = redisService.getAllKeys();
        List<String> KeyCollect = allKeys.stream().filter(key -> key.startsWith("token_")).collect(Collectors.toList());
        for (String all : KeyCollect) {
            String token = redisService.get(all);
            String user = jwtUtils.getUsernameFromToken(token);
            if (user.equals(username)) {
                redisService.del(all);
            }
        }
        return Result.ok().message("成功");
    }
}
